<!-- 个人资料 -->
<template>
    <div class="user-setting">
        <el-card class="!border-none" shadow="never">
            <el-form
                ref="formRef"
                class="ls-form"
                :model="formData"
                :rules="rules"
                label-width="100px"
            >
                <el-form-item label="头像：" prop="avatar">
                    <div class="avatar-upload-container">
                        <div class="avatar-preview" v-if="formData.avatar">
                            <img :src="formData.avatar" alt="头像预览" class="avatar-image" />
                        </div>
                        <div class="avatar-placeholder" v-else>
                            <el-icon :size="48" color="#ccc">
                                <Avatar />
                            </el-icon>
                            <p>点击上传头像</p>
                        </div>
                        <el-upload
                            ref="uploadRef"
                            class="avatar-uploader"
                            :show-file-list="false"
                            :before-upload="beforeAvatarUpload"
                            :http-request="handleAvatarUpload"
                            accept="image/*"
                        >
                            <el-button type="primary" size="small" :loading="avatarUploading">
                                {{ avatarUploading ? '上传中...' : '更换头像' }}
                            </el-button>
                        </el-upload>
                    </div>
                </el-form-item>

                <el-form-item label="账号：" prop="account">
                    <div class="w-80">
                        <el-input v-model="formData.account" disabled />
                    </div>
                </el-form-item>

                <el-form-item label="名称：" prop="name">
                    <div class="w-80">
                        <el-input v-model="formData.name" placeholder="请输入名称" />
                    </div>
                </el-form-item>

                <el-form-item label="当前密码：" prop="password_old">
                    <div class="w-80">
                        <el-input
                            v-model.trim="formData.password_old"
                            placeholder="修改密码时必填, 不修改密码时留空"
                            type="password"
                            show-password
                        />
                    </div>
                </el-form-item>

                <el-form-item label="新的密码：" prop="password">
                    <div class="w-80">
                        <el-input
                            v-model.trim="formData.password"
                            placeholder="修改密码时必填, 不修改密码时留空"
                            type="password"
                            show-password
                        />
                    </div>
                </el-form-item>

                <el-form-item label="确定密码：" prop="password_confirm">
                    <div class="w-80">
                        <el-input
                            v-model.trim="formData.password_confirm"
                            placeholder="修改密码时必填, 不修改密码时留空"
                            type="password"
                            show-password
                        />
                    </div>
                </el-form-item>
            </el-form>
        </el-card>
        <footer-btns>
            <el-button type="primary" @click="handleSubmit">保存</el-button>
        </footer-btns>
    </div>
</template>

<script setup lang="ts" name="userSetting">
import type { FormInstance, UploadRequestOptions } from 'element-plus'
import { Avatar } from '@element-plus/icons-vue'
import axios from 'axios'
import SparkMD5 from 'spark-md5'

import { setUserInfo } from '@/api/user'
import { multipartInit } from '@/api/setting/user'
import useUserStore from '@/stores/modules/user'
import feedback from '@/utils/feedback'

const formRef = ref<FormInstance>()
const uploadRef = ref()
const userStore = useUserStore()

// 头像上传状态
const avatarUploading = ref(false)

// 表单数据
const formData = reactive({
    avatar: '', // 头像
    account: '', // 账号
    name: '', // 名称
    password_old: '', // 当前密码
    password: '', // 新的密码
    password_confirm: '' // 确定密码
})

// 表单校验规则
const rules = reactive<object>({
    avatar: [
        {
            required: true,
            message: '头像不能为空',
            trigger: ['change']
        }
    ],
    name: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['blur']
        }
    ]
})

// 获取个人设置
const getUser = async () => {
    const userInfo = userStore.userInfo
    for (const key in formData) {
        //@ts-ignore
        formData[key] = userInfo[key]
    }
}

// 设置个人设置
const setUser = async () => {
    if (formData.password_old || formData.password || formData.password_confirm) {
        if (!formData.password_old) {
            return feedback.msgError('请输入当前密码')
        }

        if (!formData.password) {
            return feedback.msgError('请输入新的密码')
        }

        if (!formData.password_confirm) {
            return feedback.msgError('请输入确定密码')
        }

        if (formData.password_confirm != formData.password) {
            return feedback.msgError('两次输入的密码不一样')
        }
    }

    if (formData.password_old && formData.password && formData.password_confirm) {
        if (formData.password_old.length < 6 || formData.password_old.length > 32) {
            return feedback.msgError('密码长度在6到32之间')
        }
        if (formData.password.length < 6 || formData.password.length > 32) {
            return feedback.msgError('密码长度在6到32之间')
        }
        if (formData.password_confirm.length < 6 || formData.password_confirm.length > 32) {
            return feedback.msgError('密码长度在6到32之间')
        }
    }
    await setUserInfo(formData)
    userStore.getUserInfo()
}

/**
 * 计算文件MD5
 */
const calculateFileMD5 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
        const spark = new SparkMD5.ArrayBuffer()
        const fileReader = new FileReader()
        const chunkSize = 10 * 1024 * 1024 // 10MB
        let currentChunk = 0
        const totalChunks = Math.ceil(file.size / chunkSize)

        const loadNext = () => {
            const start = currentChunk * chunkSize
            const end = Math.min(start + chunkSize, file.size)
            const chunk = file.slice(start, end)

            fileReader.onload = (e) => {
                spark.append(e.target?.result as ArrayBuffer)
                currentChunk++

                if (currentChunk < totalChunks) {
                    loadNext()
                } else {
                    resolve(spark.end())
                }
            }

            fileReader.onerror = reject
            fileReader.readAsArrayBuffer(chunk)
        }

        loadNext()
    })
}

/**
 * 上传分片
 */
const uploadChunk = async (chunk: Blob, uploadUrl: string) => {
    await axios.put(uploadUrl, chunk, {
        headers: {
            'Content-Type': 'application/octet-stream'
        }
    })
}

/**
 * 头像上传前的校验
 */
const beforeAvatarUpload = (file: File) => {
    // 检查文件类型
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
        feedback.msgError('只能上传图片文件！')
        return false
    }

    // 检查文件大小（限制为10MB）
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
        feedback.msgError('图片大小不能超过10MB！')
        return false
    }

    return true
}

/**
 * 处理头像上传
 */
const handleAvatarUpload = async (options: UploadRequestOptions) => {
    const { file } = options
    
    try {
        avatarUploading.value = true
        
        // 计算文件MD5
        const fileMd5 = await calculateFileMD5(file as File)
        
        const chunkSize = 10 * 1024 * 1024 // 10MB分片大小
        const totalChunks = Math.ceil(file.size / chunkSize)
        
        // 准备上传参数
        const uploadParams = {
            filename: file.name,
            partCount: totalChunks,
            md5: fileMd5
        }
        
        // 初始化上传
        const initRes = await multipartInit(uploadParams)
        
        if (!initRes) {
            throw new Error('初始化上传失败')
        }
        
        const { uploadUrls, previewUrl } = initRes
        
        // 分片上传
        for (let i = 0; i < totalChunks; i++) {
            const start = i * chunkSize
            const end = Math.min(start + chunkSize, file.size)
            const chunk = file.slice(start, end)
            
            await uploadChunk(chunk, uploadUrls[i])
        }
        
        // 更新头像URL
        formData.avatar = previewUrl
        feedback.msgSuccess('头像上传成功！')
        
    } catch (error) {
        console.error('头像上传失败:', error)
        feedback.msgError('头像上传失败，请重试')
    } finally {
        avatarUploading.value = false
    }
}

// 提交数据
const handleSubmit = async () => {
    await formRef.value?.validate()
    setUser()
}

getUser()
</script>

<style lang="scss" scoped>
.avatar-upload-container {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;

    .avatar-preview {
        width: 80px;
        height: 80px;
        border-radius: 8px;
        overflow: hidden;
        border: 1px solid #dcdfe6;

        .avatar-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    }

    .avatar-placeholder {
        width: 80px;
        height: 80px;
        border: 2px dashed #dcdfe6;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #909399;
        font-size: 12px;

        p {
            margin: 4px 0 0 0;
        }
    }

    .avatar-uploader {
        :deep(.el-upload) {
            border: none;
        }
    }
}
</style>
